import React, { useEffect, useState } from 'react'
import {Card, Row, Col,Select, message, Form, Cascader, DatePicker, Button} from "antd";
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined, LoadingOutlined, SearchOutlined, SyncOutlined, EyeOutlined } from '@ant-design/icons'
import '../style.css'
import '../../../DepartmentManage/views/style.css'
import AtDormPie from "./AtDormPie";
import AtDormTable from "./AtDormTable";
import {fetchRequest} from "../../../../utils/Request";
import {url} from "../../../../utils/url";
import {useRequest} from "@umijs/hooks";
import {Store} from "rc-field-form/lib/interface";
import moment from "moment";
import errorCode from "../../../../utils/errorCode";


export default function DormAnalysis() {

    interface requestParamPie {
        deptId: null | undefined | string,
        startDate: null | undefined | string,
        endDate: null | undefined | string,
    }

    interface requestParamTable {
        deptId: null | undefined | string,
        startDate: null | undefined | string,
        endDate: null | undefined | string,
        pageNum: number,
        pageSize: number,
        schoolMark: number
    }

    interface requestParamTree {
        level: number,
        treeId: null | undefined | string,
    }

    const [requestParamTable, setRequestParamTable] = useState<requestParamTable>({
        deptId: "",
        startDate: "",
        endDate: "",
        pageNum: 1,
        pageSize: 10,
        schoolMark: 2
    });
    const [requestParamPie, setRequestParamPie] = useState<requestParamPie>({
        deptId: "",
        startDate: "",
        endDate: "",
    });
    const [requestParamTree, setRequestParamTree] = useState<requestParamTree>(
        {
            "level": 0,
            "treeId": "0"
        }
    );
    const [statisticData, setStatisticData] = useState<any>([]);
    const [treeNode,setTreeNode] =useState<any>([]);
    const [tableData,setTableData] = useState<any>([])
    const [form] = Form.useForm();
    const { Option } = Select;

    useEffect(() => {
        if( isNull(requestParamTable.deptId)|| isNull(requestParamTable.startDate) || isNull(requestParamTable.endDate)){
            //doNothing
        }
        else{
            getAtDormPieDataRequest(requestParamTable)
        }
    }, [requestParamTable])

    useEffect(() => {
        getSchoolOrganizationRequest(requestParamTree)
    }, [requestParamTree])


    //请求在寝学生饼图参数
    async function getAtDormPieDataRequest(params: requestParamPie) {
        console.log(params);
        
        try {
            const json = await fetchRequest(url.GET_AT_QUERY_NUMBER, params);
            if (json.success) {
                message.destroy();
                setStatisticData( [{
                    name: "在寝",
                    value: json.data.queryNumberOfRoomResultVO.atRoom
                },
                {
                    name: "不在寝",
                    value: json.data.queryNumberOfRoomResultVO.outRoom
                },
                {
                    name: "未知",
                    value: json.data.queryNumberOfRoomResultVO.unknownSchool
                }
                ])
                setTableData(json.data.myPager)

            } else {
                message.destroy();
                message.error(json.errorMsg)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)

        }
    }

    const getAtSchoolPieData = useRequest(getAtDormPieDataRequest, {
        loadingDelay: 200,
        manual: true
    })

    //请求在校学生组织机构
    async function getSchoolOrganizationRequest(params: requestParamTree) {
        try {
            const json = await fetchRequest(url.GET_SCHOOL_ORGANIZATION, params);
            if (json.success) {
                message.destroy();
                json.data.map((item:any)=>{
                    delete item.children;
                });
                setTreeNode(json.data);

            } else {
                message.destroy();
                message.error(json.errorMsg)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)

        }
    }

    const getSchoolOrganizationData = useRequest(getSchoolOrganizationRequest, {
        loadingDelay: 200,
        manual: true
    });


    //级联函数
    const onChange = (value:any, selectedOptions:any) => {

    };

    const loadData = (selectedOptions:any) => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;

        //组装参数
        const params:requestParamTree = {
            "level": 0,
            "treeId": "0"
        };
        selectedOptions.map((item:any) => {
            params.treeId =item.treeId;
            params.level = selectedOptions.length ;
        });
        // console.log(params)

        fetchRequest(url.GET_SCHOOL_ORGANIZATION, params).
        then(json => {
            if (json.success) {
                console.log(json.data)
                json.data.map((item:any)=>{
                    delete item.children;
                });
                targetOption.children = json.data;
                // console.log(targetOption)
            } else {
                message.error(json.errMsg);
            }
        }).catch(error => {
            console.log(error);
        }).finally(() => {
            targetOption.loading = false;
            //主动刷新页面
            setTreeNode([...treeNode]);
        });

    };

    function isNull(param:any) {
        return param === "" || param == undefined;
    }

    function handleFinish(values: Store) {

        // if(values.deptId ===undefined || values.deptId === "" || values.deptId.length<=1){
        //     message.error("组织机构请至少选择到第二级！");
        if(isNull(values.deptId)){
            message.error("请选择组织机构！");
            return false;
        }

        if(isNull(values.date)){
            message.error("请选择进出时间！");
            return false;
        }

        setRequestParamTable({
            // deptId:"118917293861-0813103010314129",
            deptId:typeof values.deptId === "undefined" ? "":values.deptId[values.deptId.length-1],
            startDate: typeof values.date === "undefined" ? "" : moment(values.date[0]).format("YYYY-MM-DD HH:mm:ss"),
            endDate: typeof values.date === "undefined" ? "" : moment(values.date[1]).format("YYYY-MM-DD HH:mm:ss"),
            schoolMark:parseInt(values.schoolMark),
            pageNum: 1,
            pageSize: 10
        });
        setRequestParamPie({
            // deptId:"118917293861-0813103010314129",
            deptId:typeof values.deptId === "undefined" ? "":values.deptId[values.deptId.length-1],
            startDate: typeof values.date === "undefined" ? "" : moment(values.date[0]).format("YYYY-MM-DD HH:mm:ss"),
            endDate: typeof values.date === "undefined" ? "" : moment(values.date[1]).format("YYYY-MM-DD HH:mm:ss"),
        });



        // console.log(requestParamTable);
        // console.log(requestParamPie);
    }

    //点击重置按钮
    function handleReset() {
        form.resetFields();
        setRequestParamTable({
            deptId: "" ,
            startDate: "" ,
            endDate: "" ,
            schoolMark:parseInt("2"),
            pageNum: 1,
            pageSize: 10
        });
        setRequestParamPie({
            deptId: "" ,
            startDate: "" ,
            endDate: ""
        });
    }

    //查询框
    const searchForm = (<Card className="search-form"> <Form form={form} layout="inline" initialValues={{ schoolMark: "2" }} onFinish={handleFinish} onReset={handleReset}>

        <Form.Item className="form-control-item" name="deptId" label="组织机构">

            <Cascader
                placeholder=""
                options={treeNode}
                loadData={loadData}
                changeOnSelect
                onChange={onChange}
                style={{width:400}}
            />
        </Form.Item>

        <Form.Item className="form-control-item" name="date" label="进出时间">
            <DatePicker.RangePicker showTime/>
        </Form.Item>

        <Form.Item className="form-control-item" name="schoolMark" label="是否在寝">
            <Select style={{ width: 120 }}>
                <Option value="1">在寝</Option>
                <Option value="2">不在寝</Option>
            </Select>
        </Form.Item>

        <Form.Item className="form-control-item"  >
            <Button key="1" type="primary" icon={<SearchOutlined />} htmlType="submit" style={{ marginRight: '8px' }}>搜索</Button>
            <Button key="2" icon={<SyncOutlined />} htmlType="reset">重置</Button>

        </Form.Item>

    </Form></Card>)

    return <div>
        {searchForm}
        <div className="site-card-border-less-wrapper">
            <Row gutter={24}>
                <Col span={12}>
                    <AtDormPie data={statisticData}/>
                </Col>
                <Col span={12}>
                    <AtDormTable params={requestParamTable} tableDatas={tableData}/>
                </Col>
            </Row>
        </div>
    </div>
}
